package crypto.reference;

import crypto.util.RandomCrypto;
import crypto.util.Util;
import java.util.Vector;
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;

/**
 *
 * @author gato
 */
public class Hide {
    
    private String reference;
    private Vector invalidPos = new Vector();
    Logger logger = Logger.getLogger("crypto");
    
    public String hideIndividualKey(String text, String key) {
        
        int position = 0;
        position = RandomCrypto.getRandomInt( text.length() );
        logger.info("key: "+key);
        logger.info("position: "+position);
        
        reference = Util.convertDecimalB36(position, 1);
        reference += "#" + key.length();

        return text.substring(0, position ) + key + text.substring( position );
    }
    
    @Deprecated
    protected void saveRef( int position, String key ){
        
        for( int i=0; i < key.length()+1; i++ ){
            this.invalidPos.addElement( position + i);
        }
        
    }
    
    @Deprecated
    protected int findPosition(String text, int  position, String key){
        
        for (int i = position; i < (text.length() - position); i++) {
            if ( text.charAt(i) == key.charAt(0) ) {
                return i;
            }
        }
        
        for (int i = position - 1; i > 0; i--) {
            if ( text.charAt(i) == key.charAt(0) ) {
                return i;
            }
        }
        
        return -1;
    }
    
    @Deprecated
    protected boolean validatePosition(int position, String key){
        
        if( position == -1 ) return false;
        
        int posFinal = position + key.length();
        
        if( ( this.invalidPos.contains(position) ) ){
            return true;
        }else if( ( this.invalidPos.contains(posFinal) ) ){
            return true;
        }else{
            for( int i=0; i<key.length()+1; i=i+2 ){
                if( ( this.invalidPos.contains(position+i) ) ){
                    return true;
                }
            }
        }
        
        return false;
    }
    
    
  public String[] obtainReferences(String text, String references) {
    String[] referenceIndividual = references.split("\\|");
    String[] referenceReturn = new String[ referenceIndividual.length+1 ];
    
    for( int i=referenceIndividual.length-1; i > -1 ; i-- ){
        String ref = referenceIndividual[ i ];
        String[] referencePosition = ref.split("#");
        
        int pos = Util.convertB36Decimal(referencePosition[0]);
        int cant = Integer.parseInt(referencePosition[1]);
        
        referenceReturn[i] = text.substring(pos, (pos+cant) );
        text = text.substring(0, pos) + text.substring(pos+cant);
    }
    
    referenceReturn[ referenceIndividual.length ] = text;
    
    return referenceReturn;
  }

    public String getReference() {
        return reference+"|";
    }

}
